package org.devocean.groupbuying.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.devocean.groupbuying.dao.BoxDAO;
import org.devocean.groupbuying.domain.Box;
import org.springframework.stereotype.Repository;

@Repository
public class BoxDAOImpl implements BoxDAO {

	@PersistenceContext
	private EntityManager em;

	public List<Box> findAllBoxes() {
		return em.createQuery("SELECT b FROM Box b  LEFT JOIN FETCH b.box bb",
				Box.class).getResultList();
	}

	public long countBoxes() {
		return em.createQuery("SELECT COUNT(b) FROM Box b", Long.class)
				.getSingleResult();
	}

	public List<Box> findBoxEntries(int firstResult, int maxResults) {
		return em
				.createQuery("SELECT b FROM Box b LEFT JOIN FETCH b.box bb",
						Box.class).setFirstResult(firstResult)
				.setMaxResults(maxResults).getResultList();
	}

	public Box findBoxById(Integer id) {
		return em.find(Box.class, id);
	}

	public void deleteBox(int id) {
		final Box box = em.find(Box.class, id);
		em.remove(box);

	}

	public Box saveBoxe(Box box) {
		em.persist(box);
		return box;
	}

	public Box updateBox(Box box) {
		final Box merged = em.merge(box);
		em.flush();
		return merged;
	}

}
